package com.jwm.power.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.jwm.power.mapper.OperateMapper;
import com.jwm.power.model.common.EnumOperate;
import com.jwm.power.model.common.EnumResult;
import com.jwm.power.model.entity.*;
import com.jwm.power.model.reponse.ResponseData;
import com.jwm.power.repository.DicsRepository;
import com.jwm.power.repository.LogsRepository;
import com.jwm.power.repository.XsfwCusarchiveRepository;
import com.jwm.power.repository.XsfwCussourceRepository;
import com.jwm.power.service.CustomeService;
import com.jwm.power.util.Ut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.ServletRequestDataBinder;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Service
@Transactional
public class CustomeServiceImpl implements CustomeService {

    @Autowired
    private XsfwCusarchiveRepository xsfwCusarchiveRepository;
    @Autowired
    private XsfwCussourceRepository xsfwCussourceRepository;
    @Autowired
    private LogsRepository logsRepository;
    @Autowired
    private OperateMapper operateMapper;

    //  设置客户档案
    @Override
    public ResponseData SaveCustomes(HttpServletRequest request) {
        try {
            Users users = (Users) StpUtil.getSession().get("users");
            XsfwCusarchive model_New = new XsfwCusarchive();
            ServletRequestDataBinder binder =
                    new ServletRequestDataBinder(model_New);
            binder.bind(request);

            Integer operationType = 0;
            //  新版非空验证 Optional
            if (Optional.ofNullable(model_New.getId()).isPresent()) {
                operationType = 1;
            } else {
                String cusCode = Optional.ofNullable(users.getCustomerCode()).isPresent() ? users.getCustomerCode() : "0";
                XsfwCusarchive xsfwCusarchive = xsfwCusarchiveRepository.findFirstByCreateuseridOrderByCuscodeDesc(users.getUserid());
                if(xsfwCusarchive != null){
                    cusCode = xsfwCusarchive.getCuscode();
                }
                model_New.setCuscode(String.format("%08d", Integer.parseInt(cusCode) + 1));
                model_New.setStatus(0);
            }
            model_New.setCusclass(users.getCustomerType() );
            model_New.setCusclasscode(users.getCustomerType().equals("国内") ? "01" : "02");
            String firstdate = request.getParameter("firstdate");
            model_New.setFirstdate(Ut.formatStrToDate(firstdate, "yyyy-MM-dd"));
            model_New.setCreatedate(Ut.getCurrentTime());
            model_New.setCreateuserid(users.getUserid());
            model_New.setCreateuser(users.getName());
            xsfwCusarchiveRepository.save(model_New);

            //  添加日志
            Logs log = Ut.SaveLog("cus", model_New.getCusname(), operationType == 1 ? EnumOperate.EDIT : EnumOperate.ADD, users);
            logsRepository.save(log);

            System.out.println("添加成功啦"+ EnumResult.SUCCESS + "这个就是：" + model_New);
            return new ResponseData(EnumResult.SUCCESS, model_New);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseData(EnumResult.Exception.getCode(), e.getMessage(), null);
        }
    }

    //  设置客户来源
    @Override
    public ResponseData SaveCusSources(HttpServletRequest request) {
        try {
            Users users = (Users) StpUtil.getSession().get("users");
            XsfwCussource model_New = new XsfwCussource();
            ServletRequestDataBinder binder =
                    new ServletRequestDataBinder(model_New);
            binder.bind(request);
            String a = model_New.getParentcode();
            if (!Optional.ofNullable(model_New.getParentcode()).isPresent()) {
                model_New.setParentcode("00");
            }

            Integer operationType = 0;
            if (Optional.ofNullable(model_New.getId()).isPresent()) {
                operationType = 1;
            } else {
                String maxCode = xsfwCussourceRepository.getMaxCode(model_New.getParentcode());
                maxCode = maxCode != null ? maxCode : "0";
                String parentCode = model_New.getParentcode().equals("00") ? "" : model_New.getParentcode();
                model_New.setCode(parentCode + String.format("%02d", Integer.parseInt(maxCode) + 1));
//                Integer sn_temp =  xsfwCussourceRepository.getMaxSn(model_New.getParentcode());
//                Integer sn = sn_temp != null ? sn_temp : 0;
//                model_New.setOrderbyid(sn + 1);
//                model_New.setIsLast(1);
                //  修改父级数据
                Map<String, Object> map = new HashMap<>();
                map.put("tName", "Xsfw_CusSource");
                map.put("values", "Is_Last=0");
                map.put("strWhere", " where code ='" + model_New.getParentcode() + "'");
                operateMapper.updateDefined(map);   //
            }

            model_New.setCreatedate(Ut.getCurrentTime());
            model_New.setCreateuserid(users.getUserid());
            model_New.setCreateuser(users.getName());
            model_New.setDatatype(StpUtil.hasPermission("sources.type") ? 1 : 0);
            xsfwCussourceRepository.save(model_New);

            //  添加日志
            Logs log = Ut.SaveLog("cusSource", model_New.getTitle(), operationType == 1 ? EnumOperate.EDIT : EnumOperate.ADD, users);
            logsRepository.save(log);
            return new ResponseData(EnumResult.SUCCESS, model_New);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseData(EnumResult.Exception.getCode(), e.getMessage(), null);
        }
    }
}
